import React, { useState, useEffect, useCallback } from 'react';
import { Space, Button, Table, Modal, message, Form, Input } from 'antd';
import './style.scss';
import Search from 'antd/lib/input/Search';
import { VariablesInfo } from 'admin/schema/BasicResource';
import { ColumnsType } from 'antd/es/table/interface';
import {
  getVariablesList,
  createVariables,
  modifyVariables,
  deleteVariables,
} from 'admin/servers/servers';
import { useForm } from 'antd/lib/form/Form';
import { Store } from 'antd/lib/form/interface';
import { deleteRowChangePageNum } from 'utils/tools';

const Variables: React.FC<{ versionId: number }> = props => {
  const [form] = useForm();
  const { versionId } = props;
  // Table loading状态
  const [tableLoading, setTableLoading] = useState<boolean>(false);
  // 当前页码
  const [current, setCurrent] = useState<number>(1);
  // 每页条数
  const [pageSize, setPageSize] = useState<number>(10);
  //  数据总数
  const [total, setTotal] = useState<number>(0);
  // Table数据
  const [variablesList, setVariablesList] = useState<VariablesInfo[]>([]);
  // 搜索内容
  const [searchText, setSearchText] = useState<string>('');

  // 删除变量：弹框显示
  const [deleteVisible, setDeleteVisible] = useState<boolean>(false);
  // 删除变量：变量ID
  const [deleteVarId, setDeleteVarId] = useState<number>(0);
  // 删除变量：确认按钮loading
  const [confirmDeleteLoading, setConfirmDeleteLoading] = useState<boolean>(false);

  // 变量操作类型 0-新增 1-编辑
  const [actionType, setActionType] = useState<0 | 1>(0);

  // 编辑变量：变量ID
  const [modifyVarId, setModifyVarId] = useState<number>(0);

  // 新增/编辑变量：弹框显示
  const [createVisible, setCreateVisible] = useState<boolean>(false);

  // 新增/编辑变量：确认按钮loading
  const [confirmCreateLoading, setConfirmCreateLoading] = useState<boolean>(false);

  // 词类每列配置
  const columns: ColumnsType<VariablesInfo> = [
    {
      title: '序号',
      dataIndex: 'key',
      key: 'key',
      render: (text, record, index) => index + 1 + pageSize * (current - 1),
    },
    {
      title: '变量名称',
      dataIndex: 'varName',
      key: 'varName',
    },
    {
      title: '描述',
      dataIndex: 'varDescribe',
      key: 'varDescribe',
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      render: text => text.substr(0, 16),
    },
    {
      title: '操作',
      key: 'operation',
      width: 200,
      render: (text, record, index) => (
        <>
          <Button
            type="link"
            onClick={() => {
              modifyVariablesAction(index);
            }}
          >
            编辑
          </Button>
          <Button
            type="link"
            onClick={() => {
              deleteVariablesAction(index);
            }}
          >
            删除
          </Button>
        </>
      ),
    },
  ];

  /**
   * Table数据加载
   */
  const initData = useCallback(async () => {
    setTableLoading(true);
    try {
      const res = await getVariablesList({
        versionId,
        pageNo: current,
        pageSize: pageSize,
        varName: searchText,
      });
      if (res.code === 0) {
        setVariablesList(res.data || []);
        setTotal(Number(res.count) || 0);
      } else {
        message.error(`${res.tips}(错误码: ${res.code})`);
      }
    } catch (error) {
      console.error(`系统异常: ${JSON.stringify(error)}`);
    }
    setTableLoading(false);
  }, [current, pageSize, searchText, versionId]);

  // 数据初始化 && 数据更新
  useEffect(() => {
    initData();
  }, [initData]);

  /**
   * 对table数据进行刷新：新增，编辑
   * @param pageNum 刷新页码
   */
  const refreshTable = async (pageNum?: number) => {
    if (pageNum) {
      current === pageNum ? initData() : setCurrent(pageNum);
    } else {
      initData();
    }
  };

  /**
   * 对table数据进行刷新：删除
   */
  function deleteFresh(size: number) {
    const newPageNum = deleteRowChangePageNum(size, total, current, pageSize);
    refreshTable(newPageNum);
  }

  /**
   * 翻页
   * @param pageNo 点击页码
   */
  const onChagneCurrent = (pageNo: number) => {
    setCurrent(pageNo);
  };
  /**
   *改变每页显示条数
   * @param current 当前页码
   * @param pageSize 每页显示条数
   */
  const onChangePageSize = (current: number, pageSize: number) => {
    setPageSize(pageSize);
  };

  /**
   * 根据变量名称搜索
   * @param text 搜索内容
   */
  const searchVariables = (text: string) => {
    text = text.trim();
    if (text !== searchText) {
      setSearchText(text);
      setCurrent(1);
    }
  };

  /**
   * 编辑操作
   * @param idx 所编辑数据的index
   */
  const modifyVariablesAction = (idx: number) => {
    console.log('编辑', idx);
    const { varId, varName, varDescribe } = variablesList[idx];

    setActionType(1);
    setModifyVarId(varId);
    setCreateVisible(true);
    form.setFieldsValue({
      varName,
      varDescribe,
    });
  };

  /**
   * 删除操作
   * @param idx 所删除数据的index
   */
  const deleteVariablesAction = (idx: number) => {
    console.log('删除', idx);
    setDeleteVarId(variablesList[idx].varId);
    setDeleteVisible(true);
  };

  /**
   * 请求删除变量接口
   * @param varId
   */
  const requestDeleteVariables = async (varId: number) => {
    setConfirmDeleteLoading(true);
    try {
      const res = await deleteVariables({
        varId,
      });
      if (res.code === 0) {
        message.success('删除成功');
        setDeleteVisible(false);
        deleteFresh(1);
      } else {
        message.error(`${res.tips}(错误码: ${res.code})`);
      }
    } catch (error) {
      console.error(`系统异常: ${JSON.stringify(error)}`);
    }

    setConfirmDeleteLoading(false);
  };

  /**
   * 请求新增变量接口
   *
   */
  const requestCreateVariables = async (varName: string, varDescribe: string) => {
    try {
      const res = await createVariables({
        versionId,
        varType: 'variable',
        varName,
        varDescribe,
      });
      if (res.code === 0) {
        // 成功
        message.success(`创建成功`);
        form.resetFields();
        setCreateVisible(false);
        refreshTable(1);
      } else {
        // 失败
        message.error(`${res.tips}(错误码: ${res.code})`);
      }
    } catch (error) {
      console.error(`系统异常: ${JSON.stringify(error)}`);
    }
  };

  /**
   * 请求编辑变量接口
   *
   */
  const requestModifyVariables = async (varName: string, varDescribe: string) => {
    try {
      const res = await modifyVariables({
        varId: modifyVarId,
        varName,
        varDescribe,
        varType: 'variable',
      });
      if (res.code === 0) {
        // 成功
        message.success(`编辑成功`);
        form.resetFields();
        setCreateVisible(false);
        refreshTable();
      } else {
        // 失败
        message.error(`${res.tips}(错误码: ${res.code})`);
      }
    } catch (error) {
      console.error(`系统异常: ${JSON.stringify(error)}`);
    }
  };

  /**
   * 确认
   */
  const onFinish = async (values: Store) => {
    console.log('onFinish -> values', values);
    setConfirmCreateLoading(true);
    const { varName, varDescribe } = values;

    if (actionType === 0) {
      // 新建词条
      requestCreateVariables(varName, varDescribe);
    } else if (actionType === 1) {
      // 编辑词条
      requestModifyVariables(varName, varDescribe);
    }

    setConfirmCreateLoading(false);
  };

  // 分页配置
  const pagination = {
    total: total,
    showTotal: (total: number) => `共 ${total} 条`,
    current: current,
    pageSize: pageSize,
    showSizeChanger: true,
    onChange: onChagneCurrent,
    onShowSizeChange: onChangePageSize,
  };
  /**
   * 新建 & 编辑词条弹框布局
   */
  const layout = {
    labelCol: { span: 6 },
    wrapperCol: { span: 16 },
  };

  return (
    <>
      <div className="basic-word-library-top">
        <Search
          placeholder="请输入变量名称"
          enterButton="搜索"
          style={{ width: 300 }}
          onSearch={searchVariables}
        />
        <div>
          <Space>
            <Button
              type="primary"
              onClick={() => {
                setActionType(0);
                setCreateVisible(true);
              }}
            >
              新建变量
            </Button>
          </Space>
        </div>
      </div>
      <div style={{ marginTop: 20 }} className="mgr-table">
        <Table
          loading={tableLoading}
          columns={columns}
          dataSource={variablesList}
          rowKey="varId"
          pagination={pagination}
        />
      </div>

      {/* 删除变量弹框 */}
      <Modal
        title="删除变量提示"
        visible={deleteVisible}
        onOk={() => {
          requestDeleteVariables(deleteVarId);
        }}
        confirmLoading={confirmDeleteLoading}
        onCancel={() => {
          setDeleteVisible(false);
        }}
      >
        <p>删除后无法恢复！确定删除吗？</p>
      </Modal>

      {/* 新建/编辑变量弹框 */}
      <Modal
        title={actionType === 0 ? '新建变量' : '编辑变量'}
        visible={createVisible}
        onOk={() => {
          form.submit();
        }}
        confirmLoading={confirmCreateLoading}
        onCancel={() => {
          form.resetFields();
          setCreateVisible(false);
        }}
      >
        <Form form={form} {...layout} onFinish={onFinish}>
          <Form.Item
            name={['varName']}
            label="变量名称"
            initialValue=""
            rules={[
              {
                required: true,
                message: '请输入50位以内英文、数字、下划线字符',
                whitespace: true,
                pattern: /^[a-zA-Z\d_]{1,50}$/,
                max: 50,
              },
            ]}
          >
            <Input.TextArea maxLength={50} placeholder="请输入50位以内英文、数字、下划线字符" />
          </Form.Item>
          <Form.Item
            name={['varDescribe']}
            label="描述"
            rules={[
              {
                message: '仅支持输入20个以内字符',
                max: 20,
              },
            ]}
          >
            <Input.TextArea maxLength={20} />
          </Form.Item>
        </Form>
      </Modal>
    </>
  );
};

export default Variables;
